<template>
  <div class="shop p-15 pt-0">
    <!-- 钱包地址 -->
    <div class="mb-15">
      <account-comp></account-comp>
    </div>

    <!-- Tabs -->
    <!-- <van-tabs shrink swipeable v-model:active="tabIndex">
      <van-tab v-for="(v, i) in tabs" :key="i" :title="v.name"></van-tab>
    </van-tabs> -->

    <!-- 商品列表 -->
    <ul>
      <li class="mt-15" v-for="(v, i) in products" :key="i">
        <!-- 封面 -->
        <img
          class="mb-10"
          style="width: 100%; border-radius: 20px"
          :src="getImageUrl(v.image)"
        />

        <!-- 介绍 -->
        <div class="box lh-2 mb-10">
          <div class="fz-16 ta-center">{{ v.name }}</div>
          <div>{{ v.content }}</div>
        </div>

        <!-- 价格 -->
        <div class="box">
          <div class="mb-10">
            <div>{{ $t('价值') }}</div>
            <div class="fz-16">{{ v.value }}{{ $t('购物券') }}</div>
          </div>

          <div class="flex flex-rb flex-cc">
            <div>
              <div>{{ $t('可获贡献值') }}</div>
              <div class="fz-16">{{ v.value }}{{ $t('贡献值') }}</div>
            </div>

            <van-button
              style="width: 100px"
              type="primary"
              round
              @click=";(currentProduct = v), (payVisible = true)"
            >
              {{ $t('下单') }}
            </van-button>
          </div>
        </div>
      </li>
    </ul>

    <!-- 下单 -->
    <van-popup v-model:show="payVisible">
      <div class="popup">
        <!-- 商品信息 -->
        <div class="flex mb-10 box p-0">
          <!-- 封面 -->
          <img
            class="mr-10"
            style="width: 90px"
            :src="getImageUrl(currentProduct.image)"
          />

          <div class="pt-10 pb-10">
            <div class="fz-16">{{ currentProduct.name }}</div>
            <div>
              {{ $t('价值') }}：{{ currentProduct.value }} ({{ $t('购物券') }})
            </div>
            <div>
              {{ $t('获得') }}：{{ currentProduct.value }} ({{ $t('贡献值') }})
            </div>
          </div>
        </div>

        <!-- 购买数量 -->
        <div class="mb-15">
          <div class="mb-10">{{ $t('购买数量') }}</div>
          <van-field
            type="digit"
            :placeholder="$t('请输入购买数量')"
            v-model="count"
          ></van-field>
        </div>

        <div class="flex flex-rc">
          <van-button
            style="width: 100px"
            type="primary"
            round
            @click="createOrder"
          >
            {{ $t('确定') }}
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import mitt from 'js/mitt'
import {
  toNumber,
  toBigNumber,
  showToast,
  showSuccess,
  showError,
  showLoading,
} from 'js/utils'
import apis from 'js/apis'

import accountComp from './account.vue'

// 余额
const coupon = inject('coupon')

// Tabs
const tabs = ref([{ name: $t('食品') }, { name: $t('百货') }])
const tabIndex = ref(0)

// 商品
const products = ref([])
const currentProduct = ref(null)

// 下单表单
const amount = ref('')
const count = ref('')
const payVisible = ref(false)

getProductList()

// 获取商品列表
async function getProductList() {
  const { code, data } = await apis.getProductList()

  if (code === 1) {
    products.value = data
  }
}

// 下单
async function createOrder() {
  amount.value = Number(currentProduct.value.value) * Number(count.value)

  if (!count.value) {
    return showToast($t('请输入购买数量'))
  }

  if (Number(coupon.value) < amount.value / 2) {
    return showToast($t('购物券不足'))
  }

  const loading = showLoading()

  try {
    // 判断用户Coupon授权给Order的额度是否足够，不够就先授权额度
    const authorizedBalanceByCoupon = await getAuthorizedBalanceByCoupon()

    if (authorizedBalanceByCoupon <= 0) {
      // 需要授权额度
      await authorizeBalanceByCoupon()
    } else if (authorizedBalanceByCoupon < amount.value / 2) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByCoupon()
    }

    // 判断用户Pandax授权给Order的额度是否足够，不够就先授权额度
    const authorizedBalanceByPandax = await getAuthorizedBalanceByPandax()

    if (authorizedBalanceByPandax <= 0) {
      // 需要授权额度
      await authorizeBalanceByPandax()
    } else if (authorizedBalanceByPandax < amount.value) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByPandax()
    }

    // 下单
    await investAmount()
    loading?.close()
  } catch (err) {
    console.error(err)
    loading?.close()
  }
}

// 下单
function investAmount() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await orderContract.context.methods
        .invest(toBigNumber(amount.value), currentProduct.value.id)
        .send({
          from: fromAddress,
        })
      count.value = ''
      payVisible.value = false
      mitt.emit('refresh')
      showSuccess($t('下单成功'))
      console.log('下单成功')
      console.log(res)
      resolve(res)
    } catch (err) {
      count.value = ''
      payVisible.value = false
      showError($t('下单失败'))
      console.error('下单失败')
      console.error(err)
      reject(err)
    }
  })
}

// Coupon授权Order额度
function authorizeBalanceByCoupon() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(100000) // 授权 100000 Coupon额度
      const res = await couponContract.context.methods
        .approve(orderContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权余额成功'))
      console.log(`授权Coupon余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError($t('授权余额失败'))
      console.error('授权Coupon余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Coupon授权给Order的额度
function getAuthorizedBalanceByCoupon() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await couponContract.context.methods
        .allowance(fromAddress, orderContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Coupon授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取授权余额失败'))
      console.error('获取Coupon授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// Pandax授权Order额度
function authorizeBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(100000) // 授权 100000 Pandax额度
      const res = await pandaxContract.context.methods
        .approve(orderContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权余额成功'))
      console.log(`授权Pandax余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError($t('授权余额失败'))
      console.error('授权Pandax余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Pandax授权给Order的额度
function getAuthorizedBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await pandaxContract.context.methods
        .allowance(fromAddress, orderContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Pandax授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取授权余额失败'))
      console.error('获取Pandax授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

function getImageUrl(url = '') {
  return (import.meta.env.VITE_API_URL_SHOP || '') + url
}
</script>

<style lang="scss" scoped></style>
